package com.snake.demo.service.impl;

import com.snake.demo.entity.LoginUser;
import com.snake.demo.entity.User;
import com.snake.demo.service.LoginService;
import com.snake.demo.utils.JwtUtil;
import com.snake.demo.utils.RedisCache;
import com.snake.demo.utils.ResponseResult;
import com.sun.deploy.net.HttpResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: snake_skin
 * @Date: 2024/05/18/12:49
 * @Description:
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    AuthenticationManager authenticationManager;

    @Resource
    RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        /**
         *  AuthenticationManager authenticate 进行用户认证
         *  进入AuthenticationManager发现authenticate方法需要传入Authentication
         *  通过idea找到Authentication的实现类有UsernamePasswordAuthenticationToken
         *  需要传入两个参数,在我们登录之前的校验,第一个参数传入用户名,第二个参数传入密码
         *  在用户认证过程中，会调用之前我们重写的账号密码校验规则 在UserDetailsServiceImpl的loadUserByUsername
         */
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 认证不成功
        if (authenticate == null) {
            throw new RuntimeException("登录失败");
        }

        // 认证通过,使用userId生成jwt,jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        Map<String,String> map = new HashMap<>();
        map.put("token", jwt);

        // 完整的用户信息存入redis,userId作为key
        redisCache.setCacheObject("login:" + userId, loginUser);

        return new ResponseResult(HttpStatus.OK.value(), "登录成功", map);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 从SecurityContextHolder中得到认证信息, 通过userId删除Redis的用户信息
        redisCache.deleteObject("login:" + loginUser.getUser().getId());
        return new ResponseResult(HttpStatus.OK.value(), "退出成功");
    }
}
